﻿using B.Z.BasicData.Domain.Entity.Authorize;
using B.Z.BasicData.ErrorCode;
using B.Z.BasicData.Infrastructure;
using MediatR;

namespace B.Z.BasicData.API.Write.Application.Menu
{
    public class RoleMenuAddCommandHandler : IRequestHandler<RoleMenuAddCommand, APIResult<int>>
    {
        private readonly IBaseRepository<T_RoleMenu> rmRepository;

        public RoleMenuAddCommandHandler(IBaseRepository<T_RoleMenu> rmRepository)
        {
            this.rmRepository = rmRepository;
        }

        public async Task<APIResult<int>> Handle(RoleMenuAddCommand request, CancellationToken cancellationToken)
        {
            APIResult<int> result = new APIResult<int>();
            result.Code = APIEnum.ok;
            result.Message = "分配成功";
            var Mlist = request.MidList.Split(",").Select(x => Convert.ToInt32(x)).ToList();


            var list = rmRepository.GetAll().Where(p=>p.Rid==request.Rid);
            if (list.Count() > 0) 
            {
                rmRepository.Del(list.ToList());
            }
            

            foreach (var item in Mlist)
            {
                T_RoleMenu menu = new T_RoleMenu();
                menu.Mid = item;
                menu.Rid = request.Rid;
                menu.CreateTime = DateTime.Now;
                result.Data += await rmRepository.Add(menu);
            }
            return await Task.FromResult(result);
        }
    }
}
